package com.king.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * Netty ByteBuf 简单使用案例
 *
 * @author unidentifiable
 * @date 2021-03-29
 */
public class NettyByteBufDemo02 {
    public static void main(String[] args) {

        // 创建一个ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer("Hello,world!", CharsetUtil.UTF_8);

        if(byteBuf.hasArray()){
            byte[] bytes = byteBuf.array();
            // 转成字符串
            System.out.println(new String(bytes, CharsetUtil.UTF_8));

            System.out.println("byteBuf = " + byteBuf);

            // 偏移量 0
            System.out.println(byteBuf.arrayOffset());
            // 0
            System.out.println(byteBuf.readerIndex());
            // 12
            System.out.println(byteBuf.writerIndex());
            // 36
            System.out.println(byteBuf.capacity());

            // 读取之后【readableBytes】可读数量减少
//            byteBuf.readByte();
//            byteBuf.getByte(0);

            // 可读的字节数
            int len = byteBuf.readableBytes();
            System.out.println(len);

            for (int i = 0; i < len; i++) {
                System.out.println((char)byteBuf.getByte(i));
            }

            // 按照某个范围读取
            System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8));
            System.out.println(byteBuf.getCharSequence(4, 6, CharsetUtil.UTF_8));
        }
    }
}
